C/C++函数传参时struct/class应该传引用还是传值?

您所在的位置:网站首页 C语言struct class C/C++函数传参时struct/class应该传引用还是传值?

C/C++函数传参时struct/class应该传引用还是传值?

2024-07-17 03:16| 来源: 网络整理| 查看: 265

C/C++函数传参时struct/class应该传引用还是传值? 一、什么是PoD数据类型?二、怎么判断一个struct/class是否为PoD类型?三、struct/class作为函数形参时,该如何传值?

一、什么是PoD数据类型?

具体可以以参考 链接1: 什么是PoD数据类型? 链接2: C++中PoD类型

二、怎么判断一个struct/class是否为PoD类型?

C++11中可以通过类模板进行判断,其新特性is_trivial可以用于判断一个struct/class是否为PoD类型。

定义如下:

template struct std::is_trivial;

is_trivial结构成员函数:value的返回值可以指示T是否为PoD类型。 当T包含默认的构造函数,那么T为trivial类型数据,即为PoD类型时,value为true;其他情况下,value为false。(关于trivial与non-trivial与PoD的关系,可参考C++ trivial和non-trivial构造函数及POD类型)

三、struct/class作为函数形参时,该如何传值?

根据上文,我们知道如何判断一个struct/class是否为PoD类型?现在我们可以看看struct/class作为形参时,不同的传值类型在效率上的区别。

我们先定义一个结构体

typedef struct NewType{ int a; long b; double c; long int d; short int e; long long f; long double g; uint8_t h; //string st; } tNewType;

很显然,该结构体为PoD类型,我们也可用is_trivial来判断。当我们加入string st (string 为non-PoD类型) 的时候,tNewType就是non-PoD类型,因为它包含自定义的构造函数,为non-trivial类型。

我们测试的思路:分别将tNewType作为函数形参进行值传递和引用传递,来看看其所花费的总时间的差异,以证明不同情况下,传递效率不同。

测试代码如下:

#include #include using namespace std; typedef struct NewType{ int a; long b; double c; long int d; short int e; long long f; long double g; uint8_t h; //string st; } tNewType; // 值传递 void Test1(tNewType nt1, tNewType nt2, tNewType nt3, tNewType nt4, tNewType nt5) { } // 引用传递 void Test2(tNewType& nt1, tNewType& nt2, tNewType& nt3, tNewType& nt4, tNewType& nt5) { } // 进行1000000次传参测试 int main() { long int n1 = 0, n2 = 0; timeval t1, t2, t3, t4; gettimeofday(&t1, nullptr); while (n1++


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3